package com.bicon.botu.mall.order.processor.task.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.order.entity.AfterSalesRecords;
import com.bicon.botu.mall.order.entity.OrderGoods;
import com.bicon.botu.mall.order.mapper.AfterSalesRecordsMapper;
import com.bicon.botu.mall.order.processor.dto.RefundRecord;
import com.bicon.botu.mall.order.processor.handler.PayRpc;
import com.bicon.botu.mall.order.service.IOrderChildService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AfterSalesTaskService {

    @Autowired
    private AfterSalesRecordsMapper afterSalesRecordsMapper;

    @Autowired
    private IOrderChildService orderChildService;

    @Autowired
    private PayRpc payRpc;

    /**
     * 调用RPC执行退款操作
     */
    @Transactional(rollbackFor = Exception.class)
    public void refund() {
        // 查询需要退款的售后申请
        List<RefundRecord> refundRecords = afterSalesRecordsMapper.queryRefundRecords();
        log.info("即将开始退款，总任务数：{}",refundRecords.size());
        // 调用RPC退款
        for (int i = 0; i < refundRecords.size(); i++) {
            RefundRecord refund = refundRecords.get(i);
            String result = payRpc.toRefund("mall", "order",refund.getPayBackAmount().toString(),
                    refund.getReason(),"BOTU",refund.getOriginalTransactionCode(),refund.getApplyNo(),refund.getReason());

            BaseResult<String> baseResult  = JSONObject.parseObject(result,new TypeReference<BaseResult<String>>(){}.getType());
            // 更新记录ID的退款状态
            if(baseResult.getCode() == Constants.RESPONSE_CODE_200){
                AfterSalesRecords records = new AfterSalesRecords();
                records.setId(refund.getId());
                records.setStatus(5);
                records.setBackTime(new Date());
                records.updateById();

                // 查询未申请退货并成功的交易明细数量
                Long count = this.afterSalesRecordsMapper.countUnAfterSalesDetail(records.getOrderGoodsId());
                if(count == 0){
                    OrderGoods goods = new OrderGoods();
                    goods.setId(refund.getOrderGoodsId());
                    goods.setPayState(5);
                    goods.updateById();
                    List<OrderGoods> orderGoodList = new ArrayList<>();
                    orderGoodList.add(goods);
                    orderChildService.insertOrderRecord("",orderGoodList,"系统自动处理退款退货");
                }
            }else{
                log.error("远程调用RPC返回错误数据：{}",result);
            }
        }
        // 检查订单是否完成了退款

    }
}
